<!-- ERC-设备巡检-巡检规则 -->
<template>
  <div>
    <div v-show="isMain" class="equip-wrap-common">
      <px-form class="custom-form-ui equip-form" :model="queryParams" label-position="right" label-width="120px">
        <px-row :gutter="16">
          <px-col :span="5">
            <px-form-item label="规则名称">
              <px-input
                v-model="queryParams.checkRuleNo"
                placeholder="请输入规则名称"
                autocomplete="off"
                maxlength="50"
                clearable
                @blur="queryParams.checkRuleNo = $event.target.value.trim()"
                @keyup.enter="queryTable"
              >
                <template #suffix>
                  <px-icon style="cursor: pointer" @click="queryTable">
                    <search />
                  </px-icon>
                </template>
              </px-input>
            </px-form-item>
          </px-col>
          <px-col :span="5">
            <px-form-item label="地块">
              <px-select v-model="queryParams.facCode" placeholder="请选择地块" filterable clearable @change="changeFacCode">
                <px-option v-for="item in facCodeList" :key="item.id" :label="item.name" :value="item.value" />
              </px-select>
            </px-form-item>
          </px-col>
          <px-col :span="5">
            <px-form-item label="巡检对象">
              <px-select v-model="queryParams.checkType" placeholder="请选择巡检对象" filterable clearable @change="queryParams.eqpTypeCodes = []">
                <px-option v-for="item in checkTypeList" :key="item.value" :label="item.name" :value="item.value" />
              </px-select>
            </px-form-item>
          </px-col>
          <px-col :span="5" v-if="queryParams.checkType === 'equipment' || queryParams.checkType === ''">
            <px-form-item label="设备类型">
              <px-tree-select
                v-model="queryParams.eqpTypeCodes"
                filterable
                clearable
                placeholder="请选择设备类型"
                :props="{
                  children: 'children',
                  label: 'name',
                  value: 'code'
                }"
                :data="eqpTypeCodeList"
                :render-after-expand="false"
              />
            </px-form-item>
          </px-col>
          <px-col :span="5" v-if="queryParams.checkType === 'environment'">
            <CheckArea :checkArea="queryParams.eqpTypeCodes" :fac-code="queryParams.facCode" @changeCheckArea="changeCheckArea" />
          </px-col>
          <px-col :span="4">
            <px-button type="primary" @click="queryTable">查询</px-button>
            <px-button @click="resetTable">重置</px-button>
          </px-col>
        </px-row>
      </px-form>
      <div v-has="'ERC_INSPECT_RULE_ADD'" class="equip-table-btn">
        <px-dropdown trigger="click" @command="handleAdd">
          <px-button type="primary"
            >新增巡检规则
            <px-icon style="margin-left: 4px"><ArrowDown /></px-icon>
          </px-button>
          <template #dropdown>
            <px-dropdown-menu>
              <px-dropdown-item v-for="item in sourceList" :key="item.value" :command="item.value">{{ item.name }}</px-dropdown-item>
            </px-dropdown-menu>
          </template>
        </px-dropdown>
      </div>
      <px-table :data="tableData" class="equip-table" size="small" height="calc(100vh - 304px)" border>
        <px-table-column label="序号" width="80" align="center" fixed="left">
          <template #default="{ $index }">
            {{ (queryParams.pageNum - 1) * queryParams.pageSize + $index + 1 }}
          </template>
        </px-table-column>
        <px-table-column
          v-for="(item, index) in tableColumns"
          :key="index"
          :label="item.label"
          :min-width="item.minWidth"
          :align="item.align"
          :show-overflow-tooltip="item.showOverflowTooltip"
          :fixed="item.fixed"
        >
          <template #default="scope">
            <px-button v-if="item.checkRuleNo && showRowText('ERC_INSPECT_RULE_VIEW')" link type="primary" @click="handleView(scope.row)">
              {{ scope.row.checkRuleNo }}
            </px-button>
            <span v-else-if="item.checkRuleNo && !showRowText('ERC_INSPECT_RULE_VIEW')">{{ scope.row.checkRuleNo }}</span>
            <span v-else-if="item.checkType">{{
              scope.row.checkType === "equipment" ? "设备" : scope.row.checkType === "environment" ? "环境" : "-"
            }}</span>
            <span v-else>{{ scope.row[item.prop] === 0 ? scope.row[item.prop] : scope.row[item.prop] ? scope.row[item.prop] : "-" }}</span>
          </template>
        </px-table-column>
        <px-table-column fixed="right" label="操作" width="180" align="center">
          <template #default="scope">
            <px-tooltip content="详情" placement="top">
              <px-button v-has="'ERC_INSPECT_RULE_VIEW'" link type="primary" icon="Tickets" @click="handleView(scope.row)" />
            </px-tooltip>
            <px-tooltip content="编辑" placement="top">
              <px-button v-has="'ERC_INSPECT_RULE_EDIT'" link type="primary" icon="EditPen" @click="handleEdit(scope.row)" />
            </px-tooltip>
            <px-tooltip content="复制" placement="top">
              <px-button v-has="'ERC_INSPECT_RULE_COPY'" link type="primary" icon="CopyDocument" @click="handleCopy(scope.row)" />
            </px-tooltip>
            <px-tooltip content="删除" placement="top">
              <px-button v-has="'ERC_INSPECT_RULE_DELETE'" link type="danger" icon="Delete" @click="handleDelete(scope.row)" />
            </px-tooltip>
          </template>
        </px-table-column>
      </px-table>
      <pagination
        v-show="total > 0"
        v-model:page="queryParams.pageNum"
        v-model:limit="queryParams.pageSize"
        class="equip-table-pagination"
        :total="total"
        @pagination="queryTable"
      />
    </div>
    <!-- 添加页面 -->
    <AddInspecDetail
      :isMain="isMain"
      :isView="isView"
      :addType="addType"
      :checkRuleNo="checkRuleNo"
      :detailPageType="detailPageType"
      :facCodeList="facCodeList"
      :eqpTypeCodeList="eqpTypeCodeList"
      @backMainPage="backMainPage"
      @queryTable="queryTable"
    />
    <!-- 查看页面 -->
    <ViewInspecDetail :isMain="isMain" :isView="isView" :checkRuleNo="checkRuleNo" :detailPageType="detailPageType" @backMainPage="backMainPage" />
  </div>
</template>

<script setup lang="ts">
defineOptions({
  name: "ERC_INSPECT_RULE"
});
import { onMounted, reactive, toRefs } from "vue";
import { useRoute, useRouter } from "vue-router";
import { PxMessage, PxMessageBox } from "px-ui";
import { showRowText } from "@/utils/pengxi";
import AddInspecDetail from "./components/AddInspecDetail.vue";
import ViewInspecDetail from "./components/ViewInspecDetail.vue";
import CheckArea from "./components/CheckArea.vue";
import { queryDictData } from "@/api/erc/common";
import { queryInspectRule, deleteInspectRule } from "@/api/erc/inspect";
import { queryEquipTypeTree } from "@/api/erc/spareParts";

const route = useRoute();
const router = useRouter();
const state = reactive<any>({
  isMain: true, // 主页面true 详情页面false
  isView: true, // 查看true 新增/编辑false
  facCodeList: [],
  eqpTypeCodeList: [],
  queryParams: {
    checkRuleNo: "",
    facCode: "",
    checkType: "",
    eqpTypeCodes: [],
    pageNum: 1,
    pageSize: 20
  },
  tableColumns: [
    { prop: "checkRuleNo", label: "规则编号", minWidth: "180", showOverflowTooltip: true, checkRuleNo: true, fixed: "left" },
    { prop: "checkRuleName", label: "巡检规则名称", minWidth: "180", showOverflowTooltip: true },
    { prop: "facName", label: "地块", minWidth: "160", showOverflowTooltip: true },
    { prop: "checkType", label: "巡检对象", minWidth: "100", showOverflowTooltip: true, checkType: true },
    { prop: "eqpTypeName", label: "设备类型/巡检区域", minWidth: "180", showOverflowTooltip: true },
    { prop: "ruleTypeName", label: "规则类型", minWidth: "120", showOverflowTooltip: true },
    { prop: "updateByName", label: "更新人", minWidth: "140", showOverflowTooltip: true },
    { prop: "updateTime", label: "更新时间", minWidth: "160", showOverflowTooltip: true }
  ],
  tableData: [],
  total: 0,
  detailPageType: "add",
  checkRuleNo: "",
  sourceList: [
    { name: "设备巡检", value: "equipment" },
    { name: "环境巡检", value: "environment" }
  ],
  checkTypeList: [
    { name: "设备", value: "equipment" },
    { name: "环境", value: "environment" }
  ],
  addType: "equipment"
});
const {
  isView,
  isMain,
  facCodeList,
  eqpTypeCodeList,
  queryParams,
  tableColumns,
  tableData,
  total,
  detailPageType,
  checkRuleNo,
  sourceList,
  checkTypeList,
  addType
} = toRefs(state);

// 进入页面时触发
onMounted(() => {
  if (route?.query && route?.query?.id) {
    checkRuleNo.value = route?.query?.id;
    isMain.value = false;
    isView.value = true;
  } else {
    isMain.value = true;
    isView.value = true;
    querySelectList();
    queryTable();
  }
});

// 获取下拉框
const querySelectList = async () => {
  facCodeList.value = await queryDictData({ typeCode: "ERC_FACTORY_AREA" });
  const params = {
    name: ""
  };
  const data: any = await queryEquipTypeTree(params);
  eqpTypeCodeList.value = data;
};
// 查询巡检清单
const queryTable = async () => {
  const params = JSON.parse(JSON.stringify(queryParams.value));
  if (params.eqpTypeCodes === "") {
    params.eqpTypeCodes = [];
  } else if (typeof params.eqpTypeCodes === "string") {
    params.eqpTypeCodes = [params.eqpTypeCodes];
  }
  const data = await queryInspectRule(params);
  tableData.value = data?.data;
  total.value = data?.total;
};
// 重置筛选条件和巡检清单
const resetTable = async () => {
  queryParams.value = {
    checkRuleNo: "",
    facCode: "",
    checkType: "",
    eqpTypeCodes: [],
    pageNum: 1,
    pageSize: 20
  };
  queryTable();
};
// 查看
const handleView = (row: any) => {
  checkRuleNo.value = row.checkRuleNo;
  isMain.value = false;
  isView.value = true;
};
// 添加
const handleAdd = command => {
  detailPageType.value = "add";
  addType.value = command;
  checkRuleNo.value = "";
  isMain.value = false;
  isView.value = false;
};
// 编辑
const handleEdit = (row: any) => {
  detailPageType.value = "edit";
  checkRuleNo.value = row.checkRuleNo;
  isMain.value = false;
  isView.value = false;
};
// 复制巡检
const handleCopy = (row: any) => {
  detailPageType.value = "copy";
  checkRuleNo.value = row.checkRuleNo;
  isMain.value = false;
  isView.value = false;
};
// 删除
const handleDelete = async (row: any) => {
  PxMessageBox.confirm(`要删除当前巡检规则编号“${row.checkRuleNo}”吗?`, "提示", {
    confirmButtonText: "删除",
    confirmButtonClass: "px-button--danger",
    cancelButtonText: "取消",
    type: "warning",
    draggable: true
  })
    .then(async () => {
      await deleteInspectRule(row.checkRuleNo);
      PxMessage.success("删除成功");
      queryTable();
    })
    .catch(() => {});
};
// 从新增/编辑/复制、详情返回主页面
const backMainPage = () => {
  isMain.value = true;
  if (route?.query && route?.query?.id) {
    router.push({ query: {} });
  }
};
// 改变巡检区域
const changeCheckArea = val => {
  if (val && val.length > 0) {
    queryParams.value.eqpTypeCodes = val.map(item => {
      const ind = item.length - 1;
      return item[ind];
    });
  } else {
    queryParams.value.eqpTypeCodes = [];
  }
};
// 改变地块字段
const changeFacCode = val => {
  if (queryParams.value.checkType === "environment") {
    queryParams.value.eqpTypeCodes = [];
  }
};
</script>

<style lang="scss" scoped>
@import url("@/views/erc/scss/table-list.scss");
</style>
